import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { CreateSqlOTmDto } from './dto/create-sql-o-tm.dto';
import { UpdateSqlOTmDto } from './dto/update-sql-o-tm.dto';
import { People } from '@/entity/people/people.entity';
import { Phone } from '@/entity/people/phone.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
export class SqlOTmService {
  constructor(@InjectRepository(People) private readonly peopleRepository: Repository<People>, @InjectRepository(Phone) private readonly phoneRepository: Repository<Phone>) { }

  /**
   * 关联
   * @param createSqlOTmDto 
   * @returns 
   */
  async create(createSqlOTmDto: CreateSqlOTmDto,) {
    // return 'This action adds a new sqlOTm';
    const person = new People();
    person.name = createSqlOTmDto.name;
    person.phones = []

    if (createSqlOTmDto.phones) {
      // 支持新增时候设置手机
      for (let i = 0; i < createSqlOTmDto.phones.length; i++) {
        const phoneEntity = new Phone();
        phoneEntity.name = createSqlOTmDto.phones[i].name;
        phoneEntity.number = createSqlOTmDto.phones[i].number;
        person.phones.push(phoneEntity);
        // 不设置级联需要手动保存
        // await this.phoneRepository.save(phoneEntity);
      }
    }

    return await this.peopleRepository.save(person);

  }

  /**
   * 创建用户，并设置手机号，手动设置级联关系
   * @param createSqlOTmDto 
   * @returns 
   */
  async create2(createSqlOTmDto: CreateSqlOTmDto,) {
    // return 'This action adds a new sqlOTm';
    const person = new People();
    person.name = createSqlOTmDto.name;
    person.phones = []

    if (createSqlOTmDto.phones) {
      // 支持新增时候设置手机
      for (let i = 0; i < createSqlOTmDto.phones.length; i++) {
        const phoneEntity = new Phone();
        phoneEntity.name = createSqlOTmDto.phones[i].name;
        phoneEntity.number = createSqlOTmDto.phones[i].number;
        person.phones.push(phoneEntity);
        // 不设置级联需要手动保存
        await this.phoneRepository.save(phoneEntity);
      }
    }

    return await this.peopleRepository.save(person);

  }

  /**
   * 修改
   * 设置了关联，只需要保存用户即可
   * @param createSqlOTmDto 
   */
  async updateData(createSqlOTmDto: CreateSqlOTmDto) {
    try {

      if (!createSqlOTmDto.id) {
        throw new HttpException('id不能为空', HttpStatus.BAD_REQUEST);
      }

      const people = await this.peopleRepository.findOne({ where: { id: createSqlOTmDto.id }, relations: ['phones'] });


      if (people) {
        people.name = createSqlOTmDto.name;


        if (createSqlOTmDto.phones) {
          // 修改，将多余的删除
          for (let i = 0; i < people.phones.length; i++) {
            const phoneItem = people.phones[i]
            const phone = createSqlOTmDto.phones.find(item => item.id === phoneItem.id);
            if (phone) {
              phoneItem.name = phone.name;
              phoneItem.number = phone.number;
            } else {
              people.phones.splice(i, 1);
              i--;
            }

          }

          // 新增,可能有新增的
          for (let i = 0; i < createSqlOTmDto.phones.length; i++) {
            const phone = createSqlOTmDto.phones[i];
            if (!phone.id) {
              const phoneEntity = new Phone();
              phoneEntity.name = phone.name;
              phoneEntity.number = phone.number;
              people.phones.push(phoneEntity);
            }
          }
        }

        // 支持返回一个对象
        return {
          message: '修改成功',
          data: await this.peopleRepository.save(people)

        }

      } else {
        throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
      }

    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_REQUEST);
    }


  }

  findAll() {
    // return `This action returns all sqlOTm`;
    return this.peopleRepository.find({ relations: ['phones'] });
  }

  findOne(id: number) {
    return this.peopleRepository.findOne({ where: { id }, relations: ['phones'] });
  }

  update(id: number, updateSqlOTmDto: UpdateSqlOTmDto) {
    return `This action updates a #${id} sqlOTm`;
  }

  remove(id: number) {
    // return `This action removes a #${id} sqlOTm`;
    return this.peopleRepository.delete(id);
  }
}
